package cn.com.pansky;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import net.vsame.url2sql.helper.Url2SqlContext;

public class PhotoDao {
	
	Connection conn = null;
	PreparedStatement pstat = null;
	Url2SqlContext c = new Url2SqlContext();
	
	public byte[] getBanner(String id) {
		conn = c.getConn();
		String sql = "SELECT * from ic54 WHERE id = ? AND removed = 'N'";
		ResultSet rs = null;
		try {
			pstat = conn.prepareStatement(sql);
			pstat.setString(1, id);
			rs = pstat.executeQuery();
			if (rs.next()) {
				InputStream in = null;
				Blob blob = (Blob) rs.getBlob("BIC106");
				if (null != blob) {

					in = blob.getBinaryStream();
					BufferedInputStream bfin = new BufferedInputStream(in);
					return this.changeImage2Bytes(bfin);
				}
			} else {
				return null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return null;
	}
	
	
	
	/**
	 * 获取人员生存认证图片
	 * @param id 图片id 
	 * @return
	 */
	public byte[] getAuthPic(String id) {
		conn = c.getConn();
		String sql = "SELECT * FROM rc06 WHERE CA011 = ?";
		ResultSet rs = null;
		try {
			pstat = conn.prepareStatement(sql);
			pstat.setString(1, id);
			rs = pstat.executeQuery();
			if (rs.next()) {
				InputStream in = null;
				Blob blob = (Blob) rs.getBlob("CA015");
				if (null != blob) {
					in = blob.getBinaryStream();
					BufferedInputStream bfin = new BufferedInputStream(in);
					return this.changeImage2Bytes(bfin);
				}
			} else {
				return null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public byte[] changeImage2Bytes(BufferedInputStream in)
			throws FileNotFoundException, IOException {
		byte[] temp = new byte[1024];
		int size = 0;
		byte[] content = null;
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
			while ((size = in.read(temp)) != -1) {
				out.write(temp, 0, size);
			}
			in.close();
			content = out.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw e;
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return content;
	}
}
